package com.feiji.manager.usermanager.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonView;
import com.feiji.manager.usermanager.commons.ApiResult;
import com.feiji.manager.usermanager.entity.SysUser;
import com.feiji.manager.usermanager.service.SysUserService;
import com.feiji.manager.usermanager.utils.PasswordEncoder;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author xinxin
 * @since 2021-03-21
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/usermanager/sys-user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    PasswordEncoder passwordEncoder;




    @GetMapping("user")
    public ApiResult queryAllUser(){
        List<SysUser> users = sysUserService.list(null);
        users.stream().forEach(user ->{
            user.setPassword("");
        });
        System.out.println(users);
        return ApiResult.ok().data("users", users);
    }

    @PostMapping("user")
    public ApiResult insertUser(SysUser sysUser){
//        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        System.out.println(sysUser);
        boolean save = sysUserService.updateById(sysUser);
        return ApiResult.ok();

    }

    @PostMapping("login")
    public ApiResult loginUser(User user){
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        SysUser result = sysUserService.getOne(queryWrapper);
        return passwordEncoder.matches(user.getPassword()
                , result!=null?result.getPassword():"") ?ApiResult.ok()
                .data("power",result.getPower())
                .data("enabled",result.getEnabled())
                :ApiResult.error();
    }

    @DeleteMapping("user")
    public ApiResult deleteUser(Integer userId){
        int result = sysUserService.changeEnale(userId, (short) 0);
        return result>0?ApiResult.ok()
                :ApiResult.error();
    }

    @PutMapping("user")
    public ApiResult updateUser(SysUser sysUser){
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUser.setEnabled(1);
        boolean update = sysUserService.save(sysUser);
        return update==true?ApiResult.ok()
                :ApiResult.error();
    }

    @Data
    private class User{
        private String username;
        private String password;
    }
}
